/**
 * 修复脚本：为已存在的贴图添加尺寸信息
 * 遍历所有项目的贴图，读取图片文件的实际尺寸并更新配置
 */

const fs = require('fs').promises;
const fsSync = require('fs');
const path = require('path');
const { imageSize: sizeOf } = require('image-size'); // ⭐ 修复：使用新版本的导入方式

const PROJECTS_DIR = path.join(__dirname, '../../projects');

/**
 * 读取贴图配置
 */
async function readTextureConfig(texturesDir, textureId) {
    try {
        const configPath = path.join(texturesDir, `${textureId}.json`);
        const data = await fs.readFile(configPath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        return null;
    }
}

/**
 * 写入贴图配置
 */
async function writeTextureConfig(texturesDir, textureId, config) {
    const configPath = path.join(texturesDir, `${textureId}.json`);
    await fs.writeFile(configPath, JSON.stringify(config, null, 2), 'utf8');
}

/**
 * 修复单个贴图的尺寸信息
 */
async function fixTextureDimensions(projectPath, textureConfig) {
    const texturePath = path.join(PROJECTS_DIR, projectPath, textureConfig.path);
    
    // 检查文件是否存在
    if (!fsSync.existsSync(texturePath)) {
        console.log(`   ⚠️  文件不存在: ${textureConfig.displayName || textureConfig.name}`);
        return false;
    }
    
    // 如果已有尺寸信息，跳过
    if (textureConfig.width && textureConfig.height) {
        console.log(`   ✓  已有尺寸: ${textureConfig.displayName || textureConfig.name} (${textureConfig.width}×${textureConfig.height})`);
        return false;
    }
    
    try {
        // 读取图片尺寸 (image-size 2.x 需要Buffer)
        const imageBuffer = fsSync.readFileSync(texturePath);
        const dimensions = sizeOf(imageBuffer);
        
        // 更新配置
        textureConfig.width = dimensions.width;
        textureConfig.height = dimensions.height;
        textureConfig.updatedAt = new Date().toISOString();
        
        // 保存配置
        const texturesDir = path.join(PROJECTS_DIR, projectPath, 'textures');
        await writeTextureConfig(texturesDir, textureConfig.id, textureConfig);
        
        console.log(`   ✅ 已修复: ${textureConfig.displayName || textureConfig.name} (${dimensions.width}×${dimensions.height})`);
        return true;
    } catch (error) {
        console.log(`   ❌ 失败: ${textureConfig.displayName || textureConfig.name} - ${error.message}`);
        return false;
    }
}

/**
 * 处理单个项目
 */
async function fixProjectTextures(projectPath) {
    const texturesDir = path.join(PROJECTS_DIR, projectPath, 'textures');
    
    // 检查贴图目录是否存在
    if (!fsSync.existsSync(texturesDir)) {
        return { total: 0, fixed: 0 };
    }
    
    try {
        // 读取所有配置文件
        const files = await fs.readdir(texturesDir);
        const configFiles = files.filter(f => f.endsWith('.json'));
        
        if (configFiles.length === 0) {
            return { total: 0, fixed: 0 };
        }
        
        console.log(`\n📂 项目: ${projectPath}`);
        console.log(`   贴图数量: ${configFiles.length}`);
        
        let fixedCount = 0;
        
        // 处理每个贴图
        for (const configFile of configFiles) {
            const textureId = path.basename(configFile, '.json');
            const config = await readTextureConfig(texturesDir, textureId);
            
            if (config) {
                const fixed = await fixTextureDimensions(projectPath, config);
                if (fixed) {
                    fixedCount++;
                }
            }
        }
        
        return { total: configFiles.length, fixed: fixedCount };
        
    } catch (error) {
        console.error(`   ❌ 处理失败:`, error.message);
        return { total: 0, fixed: 0 };
    }
}

/**
 * 主函数
 */
async function main() {
    console.log('╔════════════════════════════════════════════════════════╗');
    console.log('║          修复贴图尺寸信息                              ║');
    console.log('╚════════════════════════════════════════════════════════╝\n');
    
    try {
        // 读取所有项目
        const entries = await fs.readdir(PROJECTS_DIR, { withFileTypes: true });
        const projectDirs = entries
            .filter(entry => entry.isDirectory() && entry.name.startsWith('project-'))
            .map(entry => entry.name);
        
        console.log(`找到 ${projectDirs.length} 个项目`);
        
        let totalTextures = 0;
        let totalFixed = 0;
        
        // 处理每个项目
        for (const projectDir of projectDirs) {
            const result = await fixProjectTextures(projectDir);
            totalTextures += result.total;
            totalFixed += result.fixed;
        }
        
        // 输出统计信息
        console.log('\n╔════════════════════════════════════════════════════════╗');
        console.log('║          修复完成                                      ║');
        console.log('╚════════════════════════════════════════════════════════╝');
        console.log(`\n📊 统计信息:`);
        console.log(`   总贴图数: ${totalTextures}`);
        console.log(`   已修复: ${totalFixed}`);
        console.log(`   已有尺寸: ${totalTextures - totalFixed}`);
        console.log('');
        
    } catch (error) {
        console.error('❌ 执行失败:', error);
        process.exit(1);
    }
}

// 执行主函数
main();

